<?php
include 'db_cred.php';


# look for pre-alert reminder, and send SMS for pre-alert
# note due to lack of time, hard-coding timezone offset (-5 hr) in notification service code
$query = "select event_id, event_name, user_phone,  minute(timediff((event_dt - interval 5 hour), now())) time_left from event natural join user where (event_reminder_dt - interval 5 hour) < now() and (event_dt - interval 5 hour) > now() and is_reminder_sent = 0 and event_is_muted = 0";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {

  print "Pre-Alert Remdiner : " . $row["event_id"] . " - " . $row["event_name"] . "\n";

  $sms_recipient = $row["user_phone"];
  $sms_message = sprintf('Re: %s sending in %d http://runninglate.dyndns.org',$row["event_name"],$row["time_left"]);
  print "[$sms_recipient] $sms_message\n";
  send_sms($sms_recipient,$sms_message);

  $query2 = "update event set is_reminder_sent = 1 where event_id = " . $row[event_id];
  $result2 = mysql_query($query2) or die('Query failed: ' . mysql_error());

}

# look for running late alert, and send SMS for running late alert
$query = "select e.event_id, e.event_name, e.alert_recipients, u.user_fullname from event e, user u where e.user_name = u.user_name and (e.event_dt - interval 5 hour) < now() and e.alert_recipients is not null and e.is_alert_sent = 0 and e.event_is_muted = 0";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
  print "Running Late Alert : " . $row["event_id"] . " - " . $row["event_name"] . "\n";

  $sms_message = sprintf('%s is running late for %s',$row["user_fullname"],$row["event_name"]);
  foreach (preg_split('/[,\s]+/',$row["alert_recipients"]) as $sms_recipient)
  {
     print "[$sms_recipient] $sms_message\n";
     send_sms($sms_recipient,$sms_message);
  }
  $query2 = "update event set is_alert_sent = 1 where event_id = " . $row[event_id];
  $result2 = mysql_query($query2) or die('Query failed: ' . mysql_error());
}


# core code for sending sms
# retrieved from sudocode.net with slight modification

function send_sms($sms_recipient, $sms_message)
{

  // arvin@sudocode.net
  // url  : http://sudocode.net/article/66/sending-a-google-voice-sms-using-php/
  // date: December 28, 2010

  require_once 'class.xhttp.php';
  include 'google_credential.php';
  # google_credential.php contains 1 line, $google_password = <actual google account password>

  // Set account login info
  $data = array();
  $data['post'] = array(
    'accountType' => 'GOOGLE',
    'Email'       => 'weezeee@gmail.com',
    'Passwd'      => $google_password,
    'service'     => 'grandcentral',
    'source'      => 'sudocode.net-example-1.0' // Application's name, e.g. companyName-applicationName-versionID
  );

  $response = xhttp::fetch('https://www.google.com/accounts/ClientLogin', $data);
  
  if(!$response['successful']) {
      echo 'response: '; print_r($response);
      die();
  }

  // Extract Auth
  preg_match('/Auth=(.+)/', $response['body'], $matches);
  $auth = $matches[1];
  // You can also cache this auth value for at least 5+ minutes
  
  // Erase POST variables used on the previous xhttp call
  $data['post'] = null;
  
  // Set Authorization for authentication
  // There is no official documentation and this might change without notice
  $data['headers'] = array(
      'Authorization' => 'GoogleLogin auth='.$auth
  );
  
  $response = xhttp::fetch('https://www.google.com/voice', $data);
  
  if(!$response['successful']) {
      echo 'response: '; print_r($response);
      die();
  }
  
  // Extract _rnr_se | This value does not change* Cache this value
  preg_match("/'_rnr_se': '([^']+)'/", $response['body'], $matches);
  $rnrse = $matches[1];
  
  // $data['headers'] still contains Auth for authentication
  
  // Set SMS options
  $data['post'] = array (
      '_rnr_se'     => $rnrse,
      'phoneNumber' => '1' . $sms_recipient, // country code + area code + phone number (international notation)
      'text'        => $sms_message,
      'id'          => ''  // thread ID of message, GVoice's way of threading the messages like GMail
  );
  
  // Send the SMS
  $response = xhttp::fetch('https://www.google.com/voice/sms/send/', $data);
  
  // Evaluate the response
  $value = json_decode($response['body']);
  
  if($value->ok) {
      echo "SMS message sent! ({$data[post][phoneNumber]}: {$data[post][text]})\n";
  } else {
      echo "Unable to send SMS! Error Code ({$value->data->code})\n\n";
      echo 'response: '; print_r($response);
  }
}
?>